/**
 * Created With IntelliJ IDEA
 * Description:牛客网：JZ22 链表中倒数最后k个结点
 * https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9?tpId=13&tqId=1377477&ru=%2Fpractice%2F529d3ae5a407492994ad2a246518148a&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&sourceUrl=
 * User: DELL
 * Data: 2022-12-06
 * Time: 20:38
 */
import java.util.*;


class ListNode {
     int val;
     ListNode next = null;
    public ListNode(int val) {
        this.val = val;
    }
}


public class Solution {
    //定义两个指针fast和slow
    //其中fast先走k个结点
    //之后fast和slow一起走
    //当fast到结尾的时候，slow即为倒数第k个结点
    public ListNode FindKthToTail (ListNode pHead, int k) {
        //判空处理
        if (pHead == null) {
            return null;
        }
        ListNode fast = pHead;
        //让fast先走k步
        while (k-- != 0 && fast != null) {
            fast = fast.next;
        }
        //当原链表的元素不足k个时
        if (k != -1) {
            return null;
        }
        //fast和slow一起走
        ListNode slow = pHead;
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}